﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using Dapper;
using ExaminationSys.DataAccess.Entity;
using DapperExtensions;
using SQLinq;
using SQLinq.Dapper;


namespace ExaminationSys.DataAccess.Repository
{
    public class SectionDownloadRepository : Repository<SectionDownload>
    {
        public SectionDownloadRepository(SqlConnection context)
            : base(context)
        {
            db = context;
        }

        private SqlConnection db;

        public override SectionDownload GetById(dynamic id)
        {
            return base.ObjectSet.Get<SectionDownload>(db, id, null, null);
        }
    }

    public class SectionDownloadService
    {
        private SectionDownloadService()
        {
        }

        public List<SectionDownload> GetAll()
        {
            using (var db = DataContent.DBServer())
            {
                IUnitOfWork work = new UnitOfWork(db);
                var result = work.SectionDownload.GetList();
                return result.ToList();
            }
        }

        public List<SectionDownload> GetPublishList(string sectionId)
        {
            using (var db = DataContent.DBServer())
            {
                IUnitOfWork work = new UnitOfWork(db);
                var pg = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() };
                pg.Predicates.Add(Predicates.Field<SectionDownload>(f => f.Status, Operator.Eq, 1));
                pg.Predicates.Add(Predicates.Field<SectionDownload>(f => f.SectionID, Operator.Eq, sectionId));
                var result = work.SectionDownload.GetList(pg);
                return result.ToList();
            }
        }
        public List<SectionDownload> GetPublishList()
        {
            using (var db = DataContent.DBServer())
            {
                IUnitOfWork work = new UnitOfWork(db);
                var pg = new PredicateGroup {Operator = GroupOperator.And, Predicates = new List<IPredicate>()};
                pg.Predicates.Add(Predicates.Field<SectionDownload>(f => f.Status, Operator.Eq, 1));
                var result = work.SectionDownload.GetList(pg);
                return result.ToList();
            }
        }


        public Guid GetTopParentId(Guid parentId)
        {
            Guid id = parentId;
            using (var db = DataContent.DBServer())
            {
                /*
                 1 1
                 2 1
                 3 2
                 4 2
                 */
                var item = db.Query(from p in new SQLinq<SectionDownload>()
                                    where p.ID == parentId
                                    select p).First();

                //if (item.ID != item.ParentID)
                //{
                //    id = GetTopParentId(item.ParentID);
                //}

                return id;
            }
        }

        public List<SectionDownload> GetListByPage(string sqlwhere, string orderbyFiled, int pagesize, int pageindex, out int totalPage, out int totalRecord)
        {
            if (string.IsNullOrWhiteSpace(orderbyFiled))
                throw new ArgumentNullException("orderbyFiled");

            if (string.IsNullOrWhiteSpace(sqlwhere))
                sqlwhere = " 1=1";
            using (var db = DataContent.DBServer())
            {
                var obj = new
                {
                    TableName = "SectionDownload",
                    Fields = "*",
                    OrderField = orderbyFiled,
                    sqlWhere = sqlwhere,
                    pageSize = pagesize,
                    pageIndex = pageindex,
                };

                var dynamicParam = new DynamicParameters(obj);
                dynamicParam.Add("TotalPage", null, DbType.Int32, ParameterDirection.Output, 32);
                dynamicParam.Add("TotalRecord", 0, DbType.Int32, ParameterDirection.Output, 32);

                var items = db.Query<SectionDownload>("PagingRecord", dynamicParam, null, true, null, CommandType.StoredProcedure);
                totalPage = dynamicParam.Get<int>("TotalPage");
                totalRecord = dynamicParam.Get<int>("TotalRecord");
                return items.ToList();
            }
        }

        public bool CheckNameExists(string name, Guid id, Guid parentId)
        {
            using (var db = DataContent.DBServer())
            {
                //var result = db.Query(from p in new SQLinq<SectionInformationrmation>()
                //                      where p.ID != id && p.Name == name && p.ParentID == parentId
                //                      select p).FirstOrDefault();
                return false; // result != null;
                //var pg = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() };
                //pg.Predicates.Add(Predicates.Field<SectionInformationrmation>(f => f.Name, Operator.Eq, name));
                //pg.Predicates.Add(Predicates.Field<SectionInformationrmation>(f => f.ID, Operator.Eq, id, true));
                //IUnitOfWork work = new UnitOfWork(db);
                //var result = work.SectionInformationrmation.GetList(pg).FirstOrDefault();
                //return result != null;
            }
        }



        public SectionDownload Get(Guid id)
        {
            using (var db = DataContent.DBServer())
            {
                IUnitOfWork work = new UnitOfWork(db);
                var result = work.SectionDownload.GetById(id);
                return result;
            }
        }
        public bool Update(SectionDownload entity)
        {
            using (var db = DataContent.DBServer())
            {
                IUnitOfWork work = new UnitOfWork(db);
                return work.SectionDownload.Update(entity);
            }
        }
        public dynamic Insert(SectionDownload entity)
        {
            using (var db = DataContent.DBServer())
            {
                IUnitOfWork work = new UnitOfWork(db);
                return work.SectionDownload.Insert(entity, null);
            }
        }

        public bool Delete(List<string> ids)
        {
            if (ids == null || ids.Count == 0) return false;
            bool flag = false;
            using (var db = DataContent.DBServer())
            {
                int retCode = 0;
                foreach (var id in ids)
                {
                    retCode = db.Execute(@"update SectionDownload set Status=0 where ID=@TmpId",
                                         new[] { new { TmpId = id } });
                    if (retCode <= 0)
                    {
                        break;

                    }
                }
                flag = true;
            }
            return flag;
        }
    }
}